// API base URL
const API_BASE_URL = 'http://localhost:5000/api';

// 获取模态框
var transportModal = document.getElementById("transportModal");
var editTransportModal = document.getElementById("editTransportModal");
var importTransportModal = document.getElementById("importTransportModal");

// 打开运输详情模态框
function openTransportModal(orderId, senderAddress, receiverAddress, status, sendTime) {
    document.getElementById("transport-order-id").textContent = orderId;
    document.getElementById("transport-sender-address").textContent = senderAddress;
    document.getElementById("transport-receiver-address").textContent = receiverAddress;
    document.getElementById("transport-status-detail").textContent = getStatusText(status);
    document.getElementById("transport-send-time").textContent = sendTime;
    transportModal.classList.add('show');
}

// 关闭运输详情模态框
function closeTransportModal() {
    transportModal.classList.remove('show');
}

// 打开编辑运输信息模态框
function openEditTransportModal(orderId, senderAddress, receiverAddress, status, sendTime) {
    document.getElementById("edit-order-id").value = orderId;
    document.getElementById("edit-sender-address").value = senderAddress;
    document.getElementById("edit-receiver-address").value = receiverAddress;
    document.getElementById("edit-status").value = status;
    document.getElementById("edit-send-time").value = sendTime;
    editTransportModal.classList.add('show');
}

// 关闭编辑运输信息模态框
function closeEditTransportModal() {
    editTransportModal.classList.remove('show');
}

// 保存运输信息更改
function saveTransportChanges() {
    const orderId = document.getElementById("edit-order-id").value;
    const senderAddress = document.getElementById("edit-sender-address").value;
    const receiverAddress = document.getElementById("edit-receiver-address").value;
    const status = document.getElementById("edit-status").value;
    const sendTime = document.getElementById("edit-send-time").value;

    // AJAX请求保存到服务器
    fetch(`${API_BASE_URL}/transport/${orderId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            sender_address: senderAddress,
            receiver_address: receiverAddress,
            status: status,
            send_time: sendTime
        })
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新表格中的显示
                const rows = document.querySelectorAll(".transport-list tbody tr");
                rows.forEach(row => {
                    if (row.cells[1].textContent === orderId) {
                        row.cells[2].textContent = senderAddress;
                        row.cells[3].textContent = receiverAddress;
                        row.cells[4].innerHTML = `<span class="transport-status transport-status-${status}">${getStatusText(status)}</span>`;
                        row.cells[5].textContent = sendTime;
                    }
                });

                closeEditTransportModal();
                alert("运输信息已更新");
            } else {
                alert("更新失败: " + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert("更新运输信息时出错");
        });
}

function getStatusText(status) {
    const statusMap = {
        'in-transit': '在途',
        'delivered': '已送达',
        'cancelled': '已取消'
    };
    return statusMap[status] || status;
}

// 打开批量导入模态框
function openImportTransportModal() {
    importTransportModal.classList.add('show');
}

// 关闭批量导入模态框
function closeImportTransportModal() {
    importTransportModal.classList.remove('show');
}

// 导出运输数据
function exportTransportData() {
    fetch(`${API_BASE_URL}/transport/export`, {
        method: 'GET',
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 创建下载链接
                let csvContent = "data:text/csv;charset=utf-8,";
                data.data.forEach(row => {
                    csvContent += row.join(",") + "\r\n";
                });

                const encodedUri = encodeURI(csvContent);
                const link = document.createElement("a");
                link.setAttribute("href", encodedUri);
                link.setAttribute("download", "运输数据.csv");
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            } else {
                alert("导出失败: " + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert("导出运输数据时出错");
        });
}

// 生成运输报告
function generateTransportReport() {
    fetch(`${API_BASE_URL}/transport/report`, {
        method: 'POST',
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert("运输报告已生成，已发送到您的邮箱");
            } else {
                alert("生成报告失败: " + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert("生成运输报告时出错");
        });
}

// 批量导入运输数据
function importTransportData() {
    const fileInput = document.getElementById("transportFileInput");
    const file = fileInput.files[0];

    if (!file) {
        alert("请选择文件");
        return;
    }

    const formData = new FormData();
    formData.append('file', file);

    fetch(`${API_BASE_URL}/transport/import`, {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert("成功导入运输数据");
                closeImportTransportModal();
                loadTransportData(); // 刷新表格数据
            } else {
                alert("导入失败: " + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert("导入运输数据时出错");
        });
}

// 下载示例CSV文件
function downloadSampleCSV() {
    fetch(`${API_BASE_URL}/transport/sample`, {
        method: 'GET',
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                let csvContent = "data:text/csv;charset=utf-8,";
                data.data.forEach(row => {
                    csvContent += row.join(",") + "\r\n";
                });

                const encodedUri = encodeURI(csvContent);
                const link = document.createElement("a");
                link.setAttribute("href", encodedUri);
                link.setAttribute("download", "运输数据模板.csv");
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            } else {
                alert("下载示例文件失败: " + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert("下载示例文件时出错");
        });
}

// 运输数据清理
function cleanTransportData() {
    if (confirm("确定要清理运输数据吗？此操作不可撤销。")) {
        fetch(`${API_BASE_URL}/transport/clean`, {
            method: 'DELETE',
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert("运输数据已清理");
                    loadTransportData(); // 刷新表格数据
                } else {
                    alert("清理失败: " + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert("清理运输数据时出错");
            });
    }
}

// 加载运输数据
function loadTransportData() {
    fetch(`${API_BASE_URL}/transport`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const tableBody = document.querySelector("#transport-list tbody");
                tableBody.innerHTML = '';

                data.data.forEach((item, index) => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                    <td class="p-2 border-b">${index + 1}</td>
                    <td class="p-2 border-b">${item.order_id}</td>
                    <td class="p-2 border-b">${item.sender_address}</td>
                    <td class="p-2 border-b">${item.receiver_address}</td>
                    <td class="p-2 border-b"><span class="transport-status transport-status-${item.status}">${getStatusText(item.status)}</span></td>
                    <td class="p-2 border-b">${item.send_time}</td>
                    <td class="p-2 border-b">
                        <button class="btn btn-sm btn-primary-custom" onclick="openTransportModal('${item.order_id}', '${item.sender_address}', '${item.receiver_address}', '${item.status}', '${item.send_time}')">查看详情</button>
                        <button class="btn btn-sm btn-warning bg-yellow-500 text-white p-1 rounded hover:bg-yellow-600">编辑</button>
                    </td>
                `;
                    tableBody.appendChild(row);
                });

                // 重新初始化数据数组和分页
                initPagination();
            } else {
                alert("加载运输数据失败: " + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert("加载运输数据时出错");
        });
}

// 初始化分页
function initPagination() {
    const table = document.getElementById('transport-list');
    const rows = table.getElementsByTagName('tr');
    allUserData = [];
    for (let i = 1; i < rows.length; i++) {
        allUserData.push({ element: rows[i] });
    }
    filteredUserData = allUserData;
    currentPage = 1;
    updateTable();
}

// 点击模态框外部时关闭模态框
window.onclick = function (event) {
    if (event.target == transportModal) {
        closeTransportModal();
    }
    if (event.target == editTransportModal) {
        closeEditTransportModal();
    }
    if (event.target == importTransportModal) {
        closeImportTransportModal();
    }
}

// 分页相关变量
var currentPage = 1;
var rowsPerPage = 5; // 每页显示5条记录
var allUserData = []; // 存储所有用户数据
var filteredUserData = []; // 存储筛选后的用户数据

// 初始化页面
document.addEventListener('DOMContentLoaded', function () {
    // 加载初始数据
    loadTransportData();

    // 绑定按钮事件
    document.querySelector('.btn-primary-custom').addEventListener('click', exportTransportData);
    document.querySelector('.btn-success').addEventListener('click', generateTransportReport);

    // 绑定高级操作下拉菜单
    const dropdownBtn = document.querySelector('.dropdown button');
    const dropdownContent = document.querySelector('.dropdown-content');

    dropdownBtn.addEventListener('click', function () {
        dropdownContent.classList.toggle('show');
    });

    // 绑定下拉菜单项
    const dropdownItems = document.querySelectorAll('.dropdown-content a');
    dropdownItems[0].addEventListener('click', openImportTransportModal);
    dropdownItems[1].addEventListener('click', cleanTransportData);

    // 绑定表格中的编辑按钮
    document.addEventListener('click', function(event) {
        if (event.target.classList.contains('btn-warning') && event.target.textContent.trim() === '编辑') {
            const row = event.target.closest('tr');
            const orderId = row.cells[1].textContent;
            const senderAddress = row.cells[2].textContent;
            const receiverAddress = row.cells[3].textContent;
            const status = row.cells[4].querySelector('span').className.includes('in-transit') ? 'in-transit' :
                row.cells[4].querySelector('span').className.includes('delivered') ? 'delivered' : 'cancelled';
            const sendTime = row.cells[5].textContent;

            openEditTransportModal(orderId, senderAddress, receiverAddress, status, sendTime);
        }
    });
});

// 更新表格显示
function updateTable() {
    // 隐藏所有行
    allUserData.forEach(user => {
        user.element.style.display = 'none';
    });

    // 显示当前页的行
    const startIndex = (currentPage - 1) * rowsPerPage;
    const endIndex = startIndex + rowsPerPage;
    const usersToShow = filteredUserData.slice(startIndex, endIndex);

    usersToShow.forEach(user => {
        user.element.style.display = '';
    });

    // 更新分页信息
    updatePaginationInfo();
}

// 渲染分页按钮
function renderPaginationButtons() {
    const totalPages = Math.ceil(filteredUserData.length / rowsPerPage);
    const paginationContainer = document.querySelector('.pagination-buttons');
    paginationContainer.innerHTML = '';

    // 最多显示5个页码按钮
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, currentPage + 2);

    if (currentPage <= 3) {
        endPage = Math.min(5, totalPages);
    }
    if (currentPage >= totalPages - 2) {
        startPage = Math.max(1, totalPages - 4);
    }

    // 第一页按钮
    if (startPage > 1) {
        const firstBtn = document.createElement('button');
        firstBtn.textContent = '1';
        firstBtn.className = 'btn btn-page';
        firstBtn.onclick = () => goToPage(1);
        paginationContainer.appendChild(firstBtn);

        if (startPage > 2) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.className = 'px-2';
            paginationContainer.appendChild(ellipsis);
        }
    }

    // 中间页码按钮
    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.textContent = i;
        pageBtn.className = 'btn btn-page' + (i === currentPage ? ' bg-blue-500 text-white' : '');
        pageBtn.onclick = () => goToPage(i);
        paginationContainer.appendChild(pageBtn);
    }

    // 最后一页按钮
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.className = 'px-2';
            paginationContainer.appendChild(ellipsis);
        }

        const lastBtn = document.createElement('button');
        lastBtn.textContent = totalPages;
        lastBtn.className = 'btn btn-page';
        lastBtn.onclick = () => goToPage(totalPages);
        paginationContainer.appendChild(lastBtn);
    }
}

// 更新分页信息
function updatePaginationInfo() {
    const totalPages = Math.ceil(filteredUserData.length / rowsPerPage);
    document.getElementById("currentPageInfo").textContent = `当前第 ${currentPage} 页，共 ${totalPages} 页，总计 ${filteredUserData.length} 条记录`;
    renderPaginationButtons();
}

// 上一页
function prevPage() {
    if (currentPage > 1) {
        currentPage--;
        updateTable();
    }
}

// 下一页
function nextPage() {
    const totalPages = Math.ceil(filteredUserData.length / rowsPerPage);
    if (currentPage < totalPages) {
        currentPage++;
        updateTable();
    }
}

// 跳转到指定页
function goToPage(page) {
    const totalPages = Math.ceil(filteredUserData.length / rowsPerPage);
    if (page >= 1 && page <= totalPages) {
        currentPage = page;
        updateTable();
    }
}

// 搜索功能
document.getElementById('search-input').addEventListener('input', function () {
    const searchValue = this.value.toLowerCase();
    filteredUserData = allUserData.filter(user => {
        const cells = user.element.getElementsByTagName('td');
        for (let j = 0; j < cells.length; j++) {
            const cellText = cells[j].textContent || cells[j].innerText;
            if (cellText.toLowerCase().indexOf(searchValue) > -1) {
                return true;
            }
        }
        return false;
    });
    currentPage = 1;
    updateTable();
});

// 筛选功能
const dateFilterInput = document.getElementById('transport-date-filter');
const statusFilterSelect = document.getElementById('transport-status-filter');
const filterButton = document.getElementById('filter-button');
const resetButton = document.getElementById('reset-button');

filterButton.addEventListener('click', function () {
    const searchValue = document.getElementById('search-input').value.toLowerCase();
    const dateFilter = dateFilterInput.value;
    const statusFilter = statusFilterSelect.value;

    filteredUserData = allUserData.filter(user => {
        const cells = user.element.getElementsByTagName('td');
        let matchSearch = false;
        let matchDate = true;
        let matchStatus = true;

        // 搜索框筛选逻辑
        for (let j = 0; j < cells.length; j++) {
            const cellText = cells[j].textContent || cells[j].innerText;
            if (cellText.toLowerCase().indexOf(searchValue) > -1) {
                matchSearch = true;
                break;
            }
        }

        // 日期筛选逻辑
        if (dateFilter) {
            const sendTimeCell = cells[5];
            const sendTime = sendTimeCell.textContent;
            matchDate = sendTime === dateFilter;
        }

        // 运输状态筛选逻辑
        if (statusFilter && statusFilter !== 'all') {
            const statusCell = cells[4];
            const currentStatus = statusCell.querySelector('span').className.includes('in-transit') ? 'in-transit' :
                statusCell.querySelector('span').className.includes('delivered') ? 'delivered' : 'cancelled';
            matchStatus = currentStatus === statusFilter;
        }

        return matchSearch && matchDate && matchStatus;
    });

    currentPage = 1;
    updateTable();
});

// 重置按钮点击事件
resetButton.addEventListener('click', function () {
    document.getElementById('search-input').value = '';
    dateFilterInput.value = '';
    statusFilterSelect.value = 'all';
    filteredUserData = allUserData;
    currentPage = 1;
    updateTable();
});

// 日期输入框变化事件
dateFilterInput.addEventListener('change', function () {
    filterButton.click();
});

// 运输状态筛选变化事件
statusFilterSelect.addEventListener('change', function () {
    filterButton.click();
});